<template>
	<view class="">
		<z-paging v-model="list" ref="paging" :default-page-size="params.pageSize" @query="queryPaging">
			<template #top>
				<view class="top-wrapper">
					<view class="top flex item-center justify-between">
						<view>
							<view class="num">{{ agentCount }}</view>
							<view>经纪人总数</view>
						</view>
						<view class="invite-btn" @click="onpeInvite">邀请经纪人</view>
					</view>
					<view class="oper-box flex item-center justify-between">
						<view v-for="(oper,i) in operMenu" :key="i" class="oper-item" @click="openPer(oper,i)">
							<uni-badge v-if="i==0" class="uni-badge-left-margin oper-item" :text="waitAuditAgentCount" absolute="rightTop" size="small">
								<image :src="oper.icon" mode="heightFix" class="oper-icon"></image>
							</uni-badge>
							<image v-else :src="oper.icon" mode="heightFix" class="oper-icon"></image>
							<view>{{oper.title}}</view>
						</view>
					</view>
				</view>
			</template>
			<view class="team-text">团队成员</view>
			<view v-for="item in list" class="team-box flex flex-col" :key="item.id" @click="detail(item)">
				<view class="flex item-center justify-between mb-16">
					<text class="font-bold">{{item.groupName}}（{{item.num}}人）</text>
					<image class="size-16" src="@/static/svg/icon-arrow-right.svg"></image>
				</view>
				<view class="flex item-center justify-between">
					<view class="flex item-center flex-col w33">
						<view>{{ item.totalOrderCount }}</view>
						<view class="gray">累计订单</view>
					</view>
					<view class="flex item-center flex-col w33">
						<view>{{ item.totalSettleCommission }}</view>
						<view class="gray">累计佣金</view>
					</view>
					<view class="flex item-center flex-col w33">
						<template v-if="item.defaultState !== 2">
							<view>{{ item.commissionRate }}%</view>
							<view class="gray">分组佣金</view>
						</template>
					</view>
				</view>
			</view>
		</z-paging>
		<sharePoster show="poster" :inviteData="inviteData" :groupData="groupData" ref="posterRef" @emitImg='emitImg'></sharePoster>
		<uni-popup ref="popup" type="center">
			<view class="fs-14 text-color-regular font-normal">
				<view class="flex justify-end mb-12">
					<image class="size-32" src="@/static/svg/icon-close.svg" @click.stop="onClose"></image>
				</view>
				<view class="uni-bg-white radius-12 pb-20" style="width:80vw;">
					<view class="fs-16 font-medium text-center p-20">请选择邀请方式</view>
					<view class="group-box px-20" @click="invite(null)">
						<view>直接邀请</view>
						<view class="gray mt-4">邀请成功后无分组</view>
					</view>
					<tempate v-if="groupList.length">
						<view class="line my-12"></view>
						<view class="group-text text-sm px-20 mb-12">按分组邀请</view>
						<view v-for="item in groupList" class="group-box px-20 pb-20" :key="item.id" @click="invite(item)">
							<view>{{item.groupName}}</view>
							<view class="gray mt-4">邀请成功直接进入该分组</view>
						</view>
					</tempate>
					
				</view>
			</view>
		</uni-popup>
		<setCommission ref="commissionRef" @refresh="getAgent2CommissionRate" showTip />
	</view>
</template>

<script setup name="Agent">
	import sharePoster from '@/pagesD/components/share-poster/share-poster.vue';
	import setCommission from '@/pagesH/components/setCommission';
	import {
		ref,
		onMounted,
		watch
	} from 'vue'
	import {
		mathHeight
	} from '@/utils/index.js'
	import {
		inviteAgent,
		unBindAgent
	} from '@/api/business.js'
	import {pageGroup, selectList} from '@/pagesD/api/group.js'
	import {getDefaultAgent2CommissionRate} from '@/pagesD/api/agent.js'
	import {onShow} from '@dcloudio/uni-app';
	import {useUserStore} from '@/stores/modules/user.js'
	const userStore = useUserStore()
	const props = defineProps({
		agentCount: {
			type: Number
		},
		waitAuditAgentCount: {
			type: Number
		}
	})
	const h = ref(0)
	const paging = ref()
	h.value = mathHeight(280)
	const triggered = ref(false)
	let groupList = ref([])
	let list = ref([])
	let total = ref(0)
	const commissionRef = ref()
	let agent2CommissionRate = ''
	const popup = ref(null)
	const groupData = ref(null)
	const operMenu = ref([{
			title: '经纪人审核',
			icon: '../static/icon-audit.svg',
			path: '/pagesD/agentAudit/agentAudit'
		},
		{
			title: '分组管理',
			icon: '../static/icon-group.svg',
			path: '/pagesD/group-manage/group-manage'
		},
		{
			title: '专属佣金',
			icon: '../static/icon-commission.svg',
			path: '/pagesH/comission/comission'
		},
		{
			title: '分销设置',
			icon: '../static/icon-distribution.svg',
			path: '/pagesH/distribution'
		}
	])
	if(userStore.userInfo.agentLevel === 2){
		operMenu.value.splice(3, 1)
	}
	const openCommission = () => {
		commissionRef.value.showPop(true, 'DEFAULT_LEVEL2_COMMISSION_RATE')
	}
	const detail = (item) => {
		uni.navigateTo({
			url:`/pagesD/group-manage/group-detail`,
			events: {
				reFreshPage: (data) => {
					reFresh()
				}
			},
			success:(res) => {
				res.eventChannel.emit('acceptData',item)
			}
		})
	}
	const params = ref({
		pageNum: 1,
		pageSize: 15
	})
	const getGroupList = async () => {
		let result = await selectList()
		if (result) {
			groupList.value = result
		}
	}

	const queryPaging = (num)=>{
		emit('updateList',{num})
		getList(num);
	}

	const getList = async (num) => {
		uni.showLoading()
		params.pageNum = num
		let result = await pageGroup({
			...params.value
		})
		if (result) {
			paging.value.complete(result.list)
		}
		uni.hideLoading()
	}
	const scrolltolower = () => {
		if (list.value.length >= total.value) {
			return
		}
		params.value.pageNum = params.value.pageNum + 1
		getList()
	}
	const onRestore = () => {
		triggered.value = false; // 需要重置
	}
	const reFresh = () => {
		list.value = []
		params.value.pageNum = 1
		getList(1)
	}
	const onRefresh = () => {
		triggered.value = true
		reFresh()
	}
	watch(() => params.value.nickName, (val) => {
		reFresh()
	})
	const changeOrderBy = (i) => {
		if (i != params.value.sortField) {
			params.value.sortField = i
			params.value.sortType = 1
		} else {
			if (params.value.sortType == 2) {
				params.value.sortField = ''
			}
			params.value.sortType = params.value.sortType == 1 ? 2 : 1
		}
		reFresh()
	}
	const onClose = () => {
		popup.value && popup.value.close()
	}
	const getAgent2CommissionRate = () => {
		getDefaultAgent2CommissionRate().then(res => {
			agent2CommissionRate = res
		})
	}
	const onpeInvite = () => {
		getAgent2CommissionRate()
		popup.value && popup.value.open()
	}
	const invite = async(item) => {
		if(item){
			if(!item.commissionRate && !userStore.userInfo.businessInfo){
				uni.showToast({
					icon: 'none',
					title: '请先设置分组佣金比例'
				})
				return
			}
			groupData.value = item
		}
		if(!item && !agent2CommissionRate && !userStore.userInfo.businessInfo){
			openCommission()
			return
		}
		if(!inviteData.value){
			await getInviteAgent()
		}
		posterRef.value.showPopPoster(true)
		onClose()
	}
	const inviteData = ref(null)
	const getInviteAgent = async () => {
		let groupId = groupData.value ? groupData.value.id : ''
		let result = await inviteAgent({ groupId })
		if(!result) return
		inviteData.value = result
		emit('getGroup', groupId, result.businessShortName, result.inviteCode)
	}
	const showPoster = ref(false)
	const posterRef = ref()
	const openPer = (item, i) => {
		uni.navigateTo({
			url:item.path,
			events: {
				reFreshPage: (data) => {
					reFresh()
				}
			}
		})
	}
	
	const emit = defineEmits(['updateNum','emitImg', 'getGroupId','updateList']);
	const delAgentById =  (item) => {
		uni.showModal({
			content: '确认与该经纪人解除关系？',
			confirmColor:'#00AEFF',
			cancelColor:'#333333',
			success: async function  (res) {
				if (res.confirm) {
					// console.log('用户点击确定');
					let result = await unBindAgent({id:item.id})
					if(result){
						uni.showToast({
							title: '解绑成功',
							icon: 'none'
						})
						reFresh()
						emit('updateNum')
					}
				} else if (res.cancel) {
					console.log('用户点击取消');
					emit('updateNum')
				}
			}
		});
	}
	const emitImg = (img) => {
		emit('emitImg',{img:img,inviteData:inviteData.value})
	}
	getGroupList()
	onShow(() => {
	  getList()
	  getGroupList()
	})

</script>

<style lang="scss" scoped>
	.w33{
		width: 33%;
	}
	.top-wrapper{
		margin: 60px 16px 0;
		background-color: #ffffff;
		border-radius: 8px;
		box-shadow: 0px 0px 6px 0px rgba(0, 0, 0, 0.05);
		.top{
			padding: 16px 26px;
			font-size: 12px;
			color: #333333;
			.num{
				font-weight: 600;
				font-size: 32px;
			}
			.invite-btn{
				border-radius: 15px;
				border: 1px solid #FA4543;
				padding: 4px 12px;
				text-align: center;
				color: #FA4543;
				background: #ffffff;
			}
		}
		.oper-box {
			border-top: 1px solid #F5F5F5;
			padding: 16px 26px;
			.oper-item {
				// width: 33.3%;
				font-size: 12px;
				font-weight: 400;
				line-height: 17px;
				text-align: center;
		
				.oper-icon {
					// width: 24px;
					height: 24px;
					margin-bottom: 6px;
				}
			}
		}
	}
	
	.team-text{
		margin: 16px;
		font-weight: 500;
		font-size: 16px;
		color: #333333;
	}

	.team-box {
		padding: 12px;
		margin: 0 16px 16px;
		background-color: #ffffff;
		border-radius: 8px;
		color: #000;
	}
	
	.gray{
		color: rgba(51,51,51,0.6);
	}
	
	.group-box{
		font-size: 13px;
		color: #333333;
	}
	
	.group-text {
		font-weight: 600;
		font-size: 14px;
		color: #333333;
	}
	
	.line{
		height: 2px;
		background: #F5F5F5;
	}

	.no-page-tit {
		font-size: 12px;
		font-weight: 400;
		line-height: 17px;
		letter-spacing: 0px;
		text-align: center;
		color: rgba(51, 51, 51, 0.6);
	}
	// 邀请
	.invite-page {
		width: 343px;
		// height: 428px;
		border-radius: 12px;
		background-color: #ffffff;
		padding: 10px;
	
		.inv-logo {
			width: 88px;
			height: 88px;
			border-radius: 12px;
			margin-bottom: 8px;
		}
	
		.inv-name {
			color: rgba(51, 51, 51, 1);
			font-size: 16px;
			font-weight: 600;
			line-height: 24px;
		}
	
		.inv-title {
			font-size: 24px;
			font-weight: 600;
			line-height: 36px;
			margin-top: 20px;
		}
	
		.inv-tip {
			font-size: 14px;
			font-weight: 400;
			line-height: 21px;
			text-align: center;
			margin-top: 10px;
		}
	
		.app-logo {
			height: 95px;
			margin: 20px auto;
		}
	
		.icon-close {
			margin-bottom: 20px;
		}
		.long-tap-inv{
			// width: Hug (152px)
			height: 22px;
			padding: 0px 8px;
			border-radius: 4px;
			background: rgba(245, 245, 245, 1);
			color: rgba(51, 51, 51, 0.6);
			font-family: PingFang SC;
			font-size: 12px;
			font-weight: 400;
			line-height: 22px;
			margin-bottom: 14px;
		}
	}
</style>